package util

import (
	"encoding/csv"
	"os"
)

func write(data []map[string]string, filename string) error {
	if len(data) == 0 {
		return nil
	}
	file, err := os.Open(filename)
	if err != nil {
		return err
	}
	defer file.Close()

	csvWriter := csv.NewWriter(file)
	//获取头顺序
	header := make([]string, len(data[0]))
	for key, _ := range data[0] {
		header = append(header, key)
	}
	//组装数据，包括头
	datas := make([][]string, len(data))
	datas = append(datas, header)
	for _, item := range data {
		data := make([]string, len(header))
		for _, key := range header {
			data = append(data, item[key])
		}
		datas = append(datas, data)
	}
	//写数据到文件
	for _, v := range datas {
		csvWriter.Write(v)
	}
	defer csvWriter.Flush()
	return err
}

func readCSVLineByLine(filename string) ([]map[string]string, error) {
	file, err := os.Open(filename)
	if err != nil {
		return nil, err
	}
	defer file.Close()

	csvReader := csv.NewReader(file)
	records, err := csvReader.ReadAll()

	header := make([]string, len(records)-1)
	result := make([]map[string]string, len(records)-1)
	//循环读取records即可，records是二维切片
	for i, record := range records {
		if i == 0 {
			for _, field := range record {
				header = append(header, field)
			}
			continue
		}
		item := make(map[string]string, len(record))
		for i, field := range record {
			item[header[i]] = field
		}
		result = append(result, item)
	}
	return result, nil
}
